package com.heihei.itextdemo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * DES加解密
 *
 */
public class DESUtil {
	private String key;
	private final String DES_TYPE = "DESede/ECB/PKCS5Padding";

	private static DESUtil instance;

	private DESUtil() {
		initKey();
	}

	public static DESUtil getInstance() {
		if (instance == null) {
			instance = new DESUtil();
		}
		return instance;
	}

	public void initKey() {
		this.key = "#s^un2ye21fcn%|a0XpR,+vh";
	}

	/**
	 * 
	 * 方法描述 加密
	 *
	 */
	public String encryptText(String sourceText) {
		try {
			byte[] plaintext;
			plaintext = sourceText.getBytes("UTF-8");
			byte[] tdesKeyData = key.getBytes("ASCII");
			Cipher c3des = Cipher.getInstance(DES_TYPE);
			SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
			c3des.init(Cipher.ENCRYPT_MODE, myKey);
			byte[] cipherText = c3des.doFinal(plaintext);
			return DatatypeConverter.printBase64Binary(cipherText);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 
	 * 对加密文字进行解密
	 */
	public String decryptText(String cipherText) {
		try {
			byte[] encData = DatatypeConverter.parseBase64Binary(cipherText);
			Cipher decipher = Cipher.getInstance(DES_TYPE);
			byte[] tdesKeyData = key.getBytes("ASCII");
			SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
			decipher.init(Cipher.DECRYPT_MODE, myKey);
			byte[] plainText = decipher.doFinal(encData);
			return new String(plainText, "UTF-8");
		} catch (Exception e) {
			return "";
		}
	}

	// 测试
	@SuppressWarnings("deprecation")
	public static void main(String args[]) {
		JSONObject obj = new JSONObject();
		obj.put("fileId", 482);
		obj.put("expireTime", System.currentTimeMillis());
		// 待加密内容
		String str = JSON.toJSONString(obj);
		String result = DESUtil.getInstance().encryptText(str);
		System.out.println("加密后：" + result);
		String t1 = URLEncoder.encode(result);
		System.out.println(t1);
		String t2 = URLDecoder.decode(t1);
		System.out.println(t2);
		System.out.println(t2.equals(result));
		System.out.println("解密后：" + DESUtil.getInstance().decryptText(result));
		System.out.println("解密后：" + DESUtil.getInstance().decryptText(t2));
	}
	

}
